package org.zwy.gradetrack.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.zwy.gradetrack.entity.CourseGoalAchievement;
import org.zwy.gradetrack.vo.CourseGoalAchievementVo;
import java.math.BigDecimal;

import java.util.List;

/**
 * 课程目标达成度Mapper接口
 */
@Mapper
public interface CourseGoalAchievementMapper extends BaseMapper<CourseGoalAchievement> {
    
    @Select("<script>" +
            "SELECT " +
            "cga.id, cga.course_id, cga.academic_year, cga.semester, cga.goal_achievement, cga.create_time, cga.update_time, " +
            "i.id AS 'indicator.id', i.indicator_code AS 'indicator.indicatorCode', i.indicator_name AS 'indicator.indicatorName', " +
            "i.requirement_id AS 'indicator.requirementId', i.description AS 'indicator.description', " +
            "i.create_time AS 'indicator.createTime', i.update_time AS 'indicator.updateTime' " +
            "FROM course_goal_achievement cga " +
            "LEFT JOIN (" +
            "    SELECT course_id, MIN(indicator_id) AS single_indicator_id " +
            "    FROM course_support_matrix " +
            "    GROUP BY course_id" +
            ") csm ON cga.course_id = csm.course_id " +
            "LEFT JOIN indicator i ON csm.single_indicator_id = i.id " +
            "<where>" +
            "  <if test=\"courseId != null\">AND cga.course_id = #{courseId}</if>" +
            "  <if test=\"academicYear != null\">AND cga.academic_year = #{academicYear}</if>" +
            "  <if test=\"semester != null\">AND cga.semester = #{semester}</if>" +
            "</where>" +
            "</script>")
    List<CourseGoalAchievementVo> getAchievementsWithIndicator(
            @Param("courseId") Integer courseId,
            @Param("academicYear") Integer academicYear,
            @Param("semester") Integer semester);

    @Select("SELECT goal_achievement FROM course_goal_achievement " +
            "WHERE course_id = #{courseId}")
    BigDecimal getGoalAchievement(Integer courseId);

    @Select("SELECT * FROM course_goal_achievement WHERE course_id = #{courseId} ORDER BY academic_year DESC, semester DESC LIMIT 1")
    CourseGoalAchievement getLatestAchievementByCourse(@Param("courseId") Integer courseId);
} 